<template>
  <div class="data-results">
    <div class="header">
      <button class="nav-button" @click="goToPreviousStep">上一步</button>
      <div class="steps-container">
        <div v-for="(step, index) in steps" :key="index" :class="['step-box', { active: index === 2 }]">
          {{ step }}
        </div>
      </div>
      <button class="nav-button" @click="goToNextStep">下一步</button>
    </div>

    <!-- 添加产品信息和碳足迹容器 -->
    <div class="info-card">
      <div class="info-content-row">
        <div class="product-name">
          <span class="info-label">产品名称：</span>
          <span class="info-value">{{ productName }}</span>
        </div>
        <div class="carbon-footprint">
          <span class="info-label">总碳足迹：</span>
          <span class="footprint-value">{{ formatNumber(totalCarbonFootprint) }}</span>
          <span class="unit">kgCO₂eq </span>
        </div>
      </div>
    </div>
    <div class="table-container">
      <div class="table-header">
        <span class="table-title">工艺流程清单</span>
      </div>
      <el-table :data="chartOut" style="width: 100%" border :span-method="objectSpanMethod">
        <!-- 生产阶段 -->
        <el-table-column prop="rowName" label="生产阶段" width="220" fixed="left">
          <template #default="{ row }">
            <div class="process-cell">
              <el-icon><Operation /></el-icon>
              <span>{{ row.rowName || "-" }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 生产活动 -->
        <el-table-column label="生产活动" prop="activity" min-width="220" align="center">
          <template #default="{ row }">
            <div class="emission-sources">
              <div class="source-wrapper">
                <span class="source-type">{{ row.activity }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 输入/输出类型 -->
        <el-table-column label="输入/输出" width="220" align="center">
          <template #default="{ row }">
            <div class="io-type">
              <template v-if="row.in_out === '输入'">
                <div class="io-item input">
                  <span>输入</span>
                </div>
              </template>
              <template v-if="row.in_out === '输出'">
                <div class="io-item output">
                  <span>输出</span>
                </div>
              </template>
              <template v-if="row.in_out === '——'">
                <div class="source-wrapper">
                  <span class="source-type">{{ row.in_out }}</span>
                </div>
              </template>
            </div>
          </template>
        </el-table-column>

        <!-- 碳排放源 -->
        <el-table-column prop="source" label="碳排放源" min-width="220" align="center">
          <template #default="{ row }">
            <div class="emission-sources">
              <div class="source-wrapper">
                <span class="source-type">{{ row.source }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 碳排因子 -->
        <!-- <el-table-column prop="factor" label="碳排因子" min-width="220" align="center">
          <template #default="{ row }">
            <div class="emission-sources">
              <div class="source-wrapper">
                <span class="source-type">{{ row.factor }}</span>
              </div>
            </div>
          </template>
        </el-table-column> -->

        <!-- 碳足迹 -->
        <el-table-column label="碳足迹" min-width="220" align="center">
          <template #default="{ row }">
            <div class="consumption-wrapper">
              <div class="consumption-item">
                <span class="amount">
                  {{ row.PCF || "——" }}
                </span>
                <span class="unit">kgCO2eq</span>
                <template v-if="row.dataSource === '分配获取'"> （工序总量） </template>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="table-container" style="margin-top: 20px">
      <!-- 单元过程碳排放值 -->
      <div class="table-header">
        <span class="table-title">单元过程碳排放值</span>
      </div>
      <div ref="echartsRef_Process" class="echarts" />
      <!-- 内外比例碳排放值 -->
      <div class="table-header">
        <span class="table-title">内外碳排放值对比</span>
      </div>
      <div ref="echartsRef_InandOut" class="echarts" />
      <!-- 外购材料碳排放值对比 -->
      <div class="table-header">
        <span class="table-title">外购碳排放值对比</span>
      </div>
      <div ref="echartsRef_outMaterial" class="echarts" />
    </div>
    <!-- <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">区块链信息</span>
      </div>
      <el-table
        :data="chartOut2"
        style="width: 100%"
        border
        :span-method="objectSpanMethod2"
        :show-header="false"
        class="blockchain-table"
      >
        <el-table-column prop="rowName" width="220" fixed="left">
          <template #default="{ row }">
            <div class="process-cell">
              <el-icon><Operation /></el-icon>
              <span>{{ row.rowName || "-" }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="childRow" min-width="220" align="center">
          <template #default="{ row }">
            <div class="emission-sources">
              <div class="source-wrapper">
                <span class="source-type">{{ row.childRow }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="source" min-width="220" align="center">
          <template #default="{ row }">
            <div class="emission-sources">
              <div class="source-wrapper">
                <span class="source-type">{{ row.source }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="value" min-width="220" align="center">
          <template #default="{ row }">
            <div class="emission-sources">
              <div class="source-wrapper">
                <span class="source-type">{{ row.value }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div> -->
  </div>
</template>

<script setup lang="ts" name="DataResults">
import { ref, onMounted, computed, watch, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import axios from "axios";
import { factorType } from "@/utils/serviceDict";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useTabsStore } from "@/stores/modules/tabs";
const tabStore = useTabsStore();
const materialList = ref();
const route = useRoute();
const router = useRouter();
const processData = ref<any[]>([]);
const steps = ref(["分配参数配置", "选择碳排放因子", "碳足迹计算结果"]);
/**用于单元过程柱状图 */
const echartsRef_Process = ref<HTMLElement>();
/**用于内外比例饼状图 */
const echartsRef_InandOut = ref<HTMLElement>();
/**用于外购材料比较饼状图 */
const echartsRef_outMaterial = ref<HTMLElement>();
let myChart_Process: echarts.ECharts | null = null;
let myChart_InandOut: echarts.ECharts | null = null;
let myChart_outMaterial: echarts.ECharts | null = null;
const isCreateLCARequestInProgress = ref(false);
const isLCAResultCreated = ref(false);
const blockchainInfo = ref<any>(null);
interface Project {
  id: number;
  productId: string;
  productName: string;
  projectEnd: string;
  projectId: string;
  projectStart: string;
  userId: number;
  companyName: string;
}
const project = ref<Project>();

const productName = ref<string>("未知产品");

/**
 * 后端返回的碳排放总览数据
 * processTotal          —— 内部工艺阶段碳排放总和
 * outMaterialTotal      —— 外购材料阶段碳排放总和
 * totalPcf              —— 总PCF（包含内部与外购）
 */
const processTotal = ref<number>(0);
const outMaterialTotal = ref<number>(0);
const eachProcessPCF = ref<{ name: string; value: number }[]>([]);
/**外购材料PCF值 */
const PCFs_outMaterial = ref();

// 页面上展示的总碳足迹（按照需求，这里展示内部工艺阶段总和）
const totalCarbonFootprint = ref<number>(0);

interface Factor {
  factorType: number;
  factorId: string;
  factorValue: number;
}
const factors = ref<Factor[]>([]);
const baseUrl = import.meta.env.VITE_BASE_URL;
// 添加数据加载状态标志
const isDataLoaded = ref(false);

// 上一步跳转
const goToPreviousStep = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/impact/index/${route.params.projectId}`);
};

// 下一步
const goToNextStep = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/interpretation/${route.params.projectId}`);
};

// 组件挂载时初始化一次
onMounted(async () => {
  const projectId = route.params.projectId?.toString();
  if (projectId) {
    await initFormData(projectId); // 先获取外购材料PCF
    await getProductInfo(); // 再获取产品信息和流程图数据
    await fetchTotalPCF(); // 再获取汇总PCF
    // 此时 getProductInfo 里的 getFlowChartData 也已完成
    if (processData.value && processData.value.length > 0) {
      const blockchainData = await ensureBlockchainInfo();
      if (blockchainData) {
        blockchainInfo.value = blockchainData;
      }
    }
  }
});

const initFormData = async (projectId: string) => {
  try {
    //数据库
    const response = await axios.get(baseUrl + "/api/carbon/getOutMaterialPCF?projectId=" + projectId);
    if (response.data && response.data.code === 200) {
      PCFs_outMaterial.value = response.data.data;
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取外购材料PCF失败";
      console.error("获取外购材料PCF错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取外购材料PCF出错:", error);
    ElMessage.error("获取外购材料PCF失败，可能是因为参数错误或网络问题");
  }
};

/**根据排放源类型获取单位标签 */
const getEmissionSourceLabel = (type: number) => {
  const source = factorType.find(f => f.value === type);
  return source ? source.label : type;
};

// 获取产品流程图数据
const getFlowChartData = async (projectId: string) => {
  if (isDataLoaded.value) {
    console.log("数据已加载，跳过获取");
    return;
  }

  console.log("开始获取碳排放数据...");

  try {
    // 获取计算结果
    const response = await axios.post(`${baseUrl}/api/carbon/getNodePCF`, { projectId: Number(projectId) });

    if (response.data.code !== 200) {
      throw new Error(response.data.msg || "获取数据失败");
    }
    console.log("从后端获取流程图数据成功:~~", response.data.data);
    const flowCharts = response.data.data;
    processData.value = flowCharts;
    isDataLoaded.value = true;
    return flowCharts;
  } catch (error) {
    console.error("获取流程图数据失败:", error);
    ElMessage.error("获取流程图数据失败");
    return null;
  }
};

// 从后端获取项目信息
const fetchProjectDetails = async (projectId: string) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0;

    const res = await axios.post(`${baseUrl}/api/carbon/getProjectById?projectId=${projectId}`, {
      userId: userId
    });
    console.log("从后端获取项目信息:", res.data);
    if (res.data?.code === 200) {
      return res.data.data;
    }
    ElMessage.warning(res.data?.msg || "获取项目信息失败");
    return null;
  } catch (error) {
    console.error("获取项目信息失败:", error);
    ElMessage.error("获取项目信息失败");
    return null;
  }
};

// 获取产品信息，碳足迹数据，外购PCF数据
const getProductInfo = async () => {
  const projectId = route.params.projectId?.toString() || "";

  // 直接从后端获取项目信息，更新产品名称
  await fetchProjectDetails(projectId).then(async details => {
    if (details) {
      project.value = details;
      productName.value = details.productName || "未知产品";
      // 获取物料清单
      try {
        const res = await axios.post(baseUrl + "/api/carbon/getMaterialsByProductId?productId=" + details.productId, {
          userId: details.userId
        });
        if (res.data && res.data.code === 200) {
          console.log("获取物料清单成功:", res.data.data);
          materialList.value = res.data.data;
        } else {
          materialList.value = [];
        }
      } catch (e) {
        materialList.value = [];
      }
    } else {
      productName.value = "未知产品";
      materialList.value = [];
    }
  });

  // 获取流程图数据
  await getFlowChartData(projectId);
  isDataLoaded.value = true;
};

/**获取汇总 PCF 数据 */
const fetchTotalPCF = async () => {
  const projectId = route.params.projectId?.toString();
  if (!projectId) return;

  try {
    const response = await axios.post(`${baseUrl}/api/carbon/CalculateTotalPCF`, {
      projectId: Number(projectId)
    });
    console.log("获取总碳足迹数据:", response.data);
    if (response.data.code !== 200) {
      throw new Error(response.data.msg || "获取总碳足迹失败");
    }

    const data = response.data.data;
    processTotal.value = data.processTotal || 0;
    outMaterialTotal.value = data.outMaterialTotal || 0;
    eachProcessPCF.value = Array.isArray(data.eachProcessPCF) ? data.eachProcessPCF : [];
    // 显示总PCF（含外购材料）
    totalCarbonFootprint.value = data.totalPcf || 0;

    // 获取到数据后重新渲染内外比例图
    window.requestAnimationFrame(() => {
      initChart_Process();
      initChart_InandOut();
    });
  } catch (error) {
    console.error("获取总碳足迹失败:", error);
    ElMessage.error("获取总碳足迹失败");
  }
};

/**展示在表格上的内容 */
const chartOut = computed(() => {
  const result: any[] = [];

  // 1. 添加外购材料信息
  if (Array.isArray(PCFs_outMaterial.value)) {
    PCFs_outMaterial.value.forEach((item: any) => {
      result.push({
        rowName: "原材料获取",
        activity: "外购" + item.materialName,
        PCF: item.PCF || "0", // PCF 为空时显示 0
        source: "——",
        factor: "——",
        in_out: "——"
      });
    });
  }

  // 2. 处理零部件生产制造和产品装配信息
  if (Array.isArray(processData.value)) {
    console.log("factors.value", factors.value);
    processData.value.forEach(flowChart => {
      // 获取物料名称
      const materialName =
        flowChart.objectType === "0"
          ? "产品装配"
          : materialList.value.find((m: any) => m.id === Number(flowChart.objectId))?.materialName || "——";

      // 遍历每个节点
      flowChart.nodes.forEach((node: any) => {
        // 判断是否为装配工序
        const rowName = flowChart.objectType === "0" ? "产品生产装配" : "零部件生产制造";
        // 处理输入节点
        node.inputNodes?.forEach((input: any) => {
          result.push({
            rowName: rowName,
            activity: materialName,
            PCF: input.inputPCF || "0", // PCF 为空时显示 0
            source: getEmissionSourceLabel(input.inputType) || "—",
            dataSource: input.dataSource || "——",
            factor: factors.value.find(f => f.factorType === input.inputType)?.factorValue || "——",
            in_out: "输入"
          });
        });

        // 处理输出节点
        node.outputNodes?.forEach((output: any) => {
          result.push({
            rowName: rowName,
            activity: materialName,
            PCF: output.outputPCF || "0", // PCF 为空时显示 0
            source: output.outputName || "——",
            factor: "——",
            in_out: "输出"
          });
        });
      });
    });
  }
  return result;
});
/**展示在表格上的内容 */
// const chartOut2 = computed(() => {
//   const result: any[] = [];
//   result.push({
//     rowName: "验证内容",
//     childRow: "计算方法",
//     source: "IPCC法",
//     value: "IPCC法"
//   });
//   for (let i = 0; i < factors.value.length; i++) {
//     const factor = factors.value[i];
//     result.push({
//       rowName: "验证内容",
//       childRow: "计算参数",
//       source: getEmissionSourceLabel(factor.factorType),
//       value: factor.factorValue
//     });
//   }
//   result.push({
//     rowName: "验证时间",
//     childRow: "2025-04-07 15:35:00",
//     source: "2025-04-07 15:35:00",
//     value: "2025-04-07 15:35:00"
//   });

//   // 使用从API获取的区块链信息
//   const previousHash = blockchainInfo.value?.previousHash || "获取中...";
//   const dataHash = blockchainInfo.value?.dataHash || "获取中...";

//   result.push({
//     rowName: "Prehash",
//     childRow: previousHash,
//     source: previousHash,
//     value: previousHash
//   });
//   result.push({
//     rowName: "Data Hash",
//     childRow: dataHash,
//     source: dataHash,
//     value: dataHash
//   });
//   result.push({
//     rowName: "验证状态",
//     childRow: "验证通过",
//     source: "验证通过",
//     value: "验证通过"
//   });
//   return result;
// });

// 修改单元格合并方法
const objectSpanMethod = ({ row, rowIndex, columnIndex }: { row: any; rowIndex: number; columnIndex: number }) => {
  if (columnIndex > 1) return { rowspan: 1, colspan: 1 };

  const prevRow = chartOut.value[rowIndex - 1];
  const getSpanCount = (condition: boolean) => {
    if (!condition) return { rowspan: 0, colspan: 0 };
    let count = 0;
    for (let i = rowIndex; i < chartOut.value.length; i++) {
      const currentRow = chartOut.value[i];
      if (columnIndex === 0 ? currentRow.rowName !== row.rowName : currentRow.activity !== row.activity) break;
      count++;
    }
    return { rowspan: count, colspan: 1 };
  };

  return getSpanCount(!prevRow || (columnIndex === 0 ? prevRow.rowName !== row.rowName : prevRow.activity !== row.activity));
};

// const objectSpanMethod2 = ({ row, rowIndex, columnIndex }: { row: any; rowIndex: number; columnIndex: number }) => {
//   // 检查同一行的第2、3、4列内容是否相同（索引1、2、3）
//   if (columnIndex === 1) {
//     // 获取当前行各列的值
//     const childRowValue = row.childRow;
//     const sourceValue = row.source;
//     const valueValue = row.value;

//     // 检查三列是否都相同
//     if (childRowValue === sourceValue && childRowValue === valueValue) {
//       // 所有内容都相同，第2列横向合并三列
//       const prevRow = chartOut2.value[rowIndex - 1];
//       const verticalMerge =
//         !prevRow || prevRow.childRow !== childRowValue ? calculateVerticalSpan(rowIndex, "childRow") : { rowspan: 0, colspan: 0 };

//       // 如果需要垂直合并，则保持垂直合并的行数，并设置跨列数为3
//       if (verticalMerge.rowspan > 0) {
//         return { rowspan: verticalMerge.rowspan, colspan: 3 };
//       } else {
//         // 如果被垂直合并隐藏，则保持隐藏状态
//         return verticalMerge;
//       }
//     }
//     // 检查第2列和第3列是否相同
//     else if (childRowValue === sourceValue) {
//       // 第2列和第3列内容相同，合并这两列
//       const prevRow = chartOut2.value[rowIndex - 1];
//       const verticalMerge =
//         !prevRow || prevRow.childRow !== childRowValue ? calculateVerticalSpan(rowIndex, "childRow") : { rowspan: 0, colspan: 0 };

//       if (verticalMerge.rowspan > 0) {
//         return { rowspan: verticalMerge.rowspan, colspan: 2 };
//       } else {
//         return verticalMerge;
//       }
//     }
//   }

//   // 新增：检查第3列和第4列是否相同
//   if (columnIndex === 2) {
//     // 检查是否应该被前一列合并
//     if (row.childRow === row.source && row.childRow === row.value) {
//       // 被第一列三列合并隐藏
//       return { rowspan: 0, colspan: 0 };
//     } else if (row.childRow === row.source) {
//       // 被第一列两列合并隐藏
//       return { rowspan: 0, colspan: 0 };
//     }
//     // 检查第3列和第4列是否相同
//     else if (row.source === row.value) {
//       // 第3、4列内容相同，合并这两列
//       return { rowspan: 1, colspan: 2 };
//     }
//   }

//   // 第4列处理：如果被第3列合并或被第1列三列合并，则隐藏
//   if (columnIndex === 3) {
//     if (row.childRow === row.source && row.childRow === row.value) {
//       // 被第一列三列合并隐藏
//       return { rowspan: 0, colspan: 0 };
//     } else if (row.source === row.value) {
//       // 被第三列合并隐藏
//       return { rowspan: 0, colspan: 0 };
//     }
//   }

//   // 只对第1列和第2列(索引0和1)进行垂直合并
//   if (columnIndex <= 1) {
//     const prevRow = chartOut2.value[rowIndex - 1];

//     // 根据列索引选择属性
//     const propName = columnIndex === 0 ? "rowName" : "childRow";

//     // 如果是第一行或者与上一行对应属性值不同
//     if (!prevRow || prevRow[propName] !== row[propName]) {
//       return { rowspan: calculateVerticalSpan(rowIndex, propName).rowspan, colspan: 1 };
//     } else {
//       // 与上一行相同，隐藏单元格
//       return { rowspan: 0, colspan: 0 };
//     }
//   }

//   // 第3列和第4列不进行垂直合并
//   return { rowspan: 1, colspan: 1 };

//   // 计算垂直方向需要合并的行数
//   function calculateVerticalSpan(startRowIndex: number, prop: string) {
//     let count = 1;
//     for (let i = startRowIndex + 1; i < chartOut2.value.length; i++) {
//       if (chartOut2.value[i][prop] !== chartOut2.value[startRowIndex][prop]) break;
//       count++;
//     }
//     return { rowspan: count, colspan: 1 };
//   }
// };

/**初始化工艺比较图 */
const initChart_Process = () => {
  // 确保容器和数据都存在
  if (!echartsRef_Process.value || !eachProcessPCF.value.length) {
    console.warn("容器或数据未就绪");
    return;
  }

  if (echartsRef_Process.value.clientWidth === 0 || echartsRef_Process.value.clientHeight === 0) {
    setTimeout(initChart_Process, 100);
    return;
  }

  if (myChart_Process) {
    myChart_Process.dispose();
    myChart_Process = null;
  }
  // 创建新实例
  myChart_Process = echarts.init(echartsRef_Process.value);

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: [
      {
        type: "category",
        data: eachProcessPCF.value.map(item => item.name),
        axisLabel: {
          interval: 0,
          rotate: 45,
          fontSize: 12
        }
      }
    ],
    yAxis: [
      {
        type: "value",
        name: "kgCO2eq",
        nameLocation: "middle",
        nameGap: 40
      }
    ],
    series: [
      {
        type: "bar",
        barWidth: "45px",
        data: eachProcessPCF.value.map(item => item.value),
        itemStyle: {
          color: "#C5D8FF",
          borderRadius: [12, 12, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: "#6B9DFE"
          }
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c} kgCO2eq"
        }
      }
    ]
  };

  myChart_Process.setOption(option);

  // 监听窗口大小变化
  const handleResize = () => {
    if (myChart_Process) {
      myChart_Process.resize();
    }
  };

  window.addEventListener("resize", handleResize);

  // 返回清理函数，供 onBeforeUnmount 使用
  return () => {
    window.removeEventListener("resize", handleResize);
    if (myChart_outMaterial) {
      myChart_outMaterial.dispose();
      myChart_outMaterial = null;
    }
  };
};

/**初始化内外图 */
const initChart_InandOut = () => {
  // 确保容器和数据都存在
  if (!echartsRef_InandOut.value || !processTotal.value || !outMaterialTotal.value) {
    console.warn("容器或数据未就绪");
    return;
  }
  if (echartsRef_InandOut.value.clientWidth === 0 || echartsRef_InandOut.value.clientHeight === 0) {
    setTimeout(initChart_InandOut, 100);
    return;
  }

  if (myChart_InandOut) {
    myChart_InandOut.dispose();
    myChart_InandOut = null;
  }
  // 创建新实例
  myChart_InandOut = echarts.init(echartsRef_InandOut.value);

  // 数据来源
  const pieData = [
    { name: "外购材料", value: outMaterialTotal.value },
    { name: "内部工艺", value: processTotal.value }
  ];

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} kgCO₂eq ({d}%)"
    },
    legend: {
      orient: "horizontal",
      bottom: "5%"
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"], // 形成环形饼图
        label: {
          show: true,
          position: "outside",
          formatter: "{b}: {c} kgCO₂eq ({d}%)"
        },
        data: pieData,
        emphasis: {
          itemStyle: {
            color: "#6B9DFE"
          }
        }
      }
    ]
  };

  myChart_InandOut.setOption(option);

  // 监听窗口大小变化
  const handleResize = () => {
    if (myChart_InandOut) {
      myChart_InandOut.resize();
    }
  };

  window.addEventListener("resize", handleResize);

  // 返回清理函数，供 onBeforeUnmount 使用
  return () => {
    window.removeEventListener("resize", handleResize);
    if (myChart_InandOut) {
      myChart_InandOut.dispose();
      myChart_InandOut = null;
    }
  };
};

/**初始化外购材料比较图 */
const initChart_outMaterial = () => {
  // 确保容器和数据都存在
  if (!echartsRef_outMaterial.value || !PCFs_outMaterial.value) {
    console.warn("容器或数据未就绪");
    return;
  }

  if (echartsRef_outMaterial.value.clientWidth === 0 || echartsRef_outMaterial.value.clientHeight === 0) {
    setTimeout(initChart_outMaterial, 100);
    return;
  }

  if (myChart_outMaterial) {
    myChart_outMaterial.dispose();
    myChart_outMaterial = null;
  }
  // 创建新实例
  myChart_outMaterial = echarts.init(echartsRef_outMaterial.value);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "10%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: PCFs_outMaterial.value.map((item: any) => item.materialName),
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: "value",
      name: "kgCO2eq",
      nameLocation: "middle",
      nameGap: 40
    },
    series: [
      {
        type: "bar",
        barWidth: "45px",
        data: PCFs_outMaterial.value.map((item: any) => item.PCF),
        itemStyle: {
          color: "#C5D8FF",
          borderRadius: [12, 12, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: "#6B9DFE"
          }
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c} kgCO2eq"
        }
      }
    ]
  };

  myChart_outMaterial.setOption(option);

  // 监听窗口大小变化
  const handleResize = () => {
    if (myChart_outMaterial) {
      myChart_outMaterial.resize();
    }
  };

  window.addEventListener("resize", handleResize);

  // 返回清理函数，供 onBeforeUnmount 使用
  return () => {
    window.removeEventListener("resize", handleResize);
    if (myChart_InandOut) {
      myChart_InandOut.dispose();
      myChart_InandOut = null;
    }
  };
};

const ensureBlockchainInfo = async () => {
  const projectId = route.params.projectId?.toString();
  if (!projectId) {
    console.error("项目ID不存在，无法获取区块链信息");
    return null;
  }
  let savedTxId = "";
  try {
    const response = await axios.get(`${baseUrl}/api/carbon/getTxId?projectId=${projectId}`);
    if (response.data && response.data.code === 200) {
      savedTxId = response.data.data.txId;
      console.log("获取到的txId:", savedTxId);
    } else {
      console.warn("获取txId失败：", response.data?.msg || "未知错误");
    }
  } catch (error) {
    console.error("请求txId出错：", error);
  }
  // 如果有保存的交易ID，尝试查询区块链信息
  if (savedTxId !== "") {
    console.log("找到已保存的交易ID，尝试查询区块链信息");
    const blockchainData = await queryBlockchainInfo(savedTxId);
    if (blockchainData) {
      isLCAResultCreated.value = true; // 标记为已创建
      console.log("成功获取区块链信息");
      return blockchainData;
    }
    console.log("使用已保存的交易ID查询失败，将尝试创建新的LCA项目结果");
  }
  let newTxId = "";
  // 没有保存的交易ID或查询失败，创建新的LCA项目结果
  if (!isLCAResultCreated.value && !isCreateLCARequestInProgress.value) {
    console.log("正在创建新的LCA项目结果...");
    newTxId = await createLCAProjectResult();
  } else {
    console.log("LCA项目结果创建已在进行中，等待完成...");
    // 等待创建完成的简单方式（可选）
    while (isCreateLCARequestInProgress.value) {
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }

  if (!newTxId) {
    console.error("创建LCA项目结果后未能获取交易ID");
    return null;
  }

  // 使用新的交易ID查询区块链信息
  console.log("使用新创建的交易ID再次查询区块链信息");
  const blockchainData = await queryBlockchainInfo(newTxId);
  console.log("查询区块链信息结果:", blockchainData);
  if (!blockchainData) {
    console.error("创建LCA项目结果后查询区块链信息失败");
    return null;
  }

  console.log("成功创建并获取区块链信息");
  return blockchainData;
};

/**根据txId查询区块链信息 */
const queryBlockchainInfo = async (txId: string) => {
  if (!txId) {
    console.error("交易ID为空，无法查询区块链信息");
    return null;
  }

  try {
    console.log("正在查询区块链信息，交易ID:", txId);
    const response = await axios.get(baseUrl + `/api/carbon/queryBlockchainDocument?txId=${txId}`);
    console.log("区块链查询结果:", response.data);
    if (response.data.data === null) {
      console.warn("区块链查询结果为空，可能是交易ID无效或数据未上链");
      return null;
    }
    if (response.data && response.data.code === 200) {
      // 更新区块链信息变量
      blockchainInfo.value = response.data.data;
      return response.data.data;
    } else {
      console.warn("区块链查询失败:", response.data?.message || "未知错误");
      return null;
    }
  } catch (error) {
    console.error("查询区块链信息时发生错误:", error);
    return null;
  }
};

// 创建LCA项目结果的接口函数
const createLCAProjectResult = async () => {
  if (!project.value) {
    console.error("项目ID未找到，无法创建LCA项目结果");
    return;
  }
  await fetchTotalPCF();
  // 如果已经创建或正在创建，则直接返回
  if (isLCAResultCreated.value || isCreateLCARequestInProgress.value) {
    console.log("LCA项目结果已创建或正在创建中，跳过重复调用");
    return;
  }
  try {
    isCreateLCARequestInProgress.value = true;
    const result: any[] = [];
    // 获取工艺信息
    processData.value.forEach((item: any) => {
      const materialName =
        item.objectType === "0"
          ? "产品装配"
          : materialList.value.find((m: any) => m.id === Number(item.objectId))?.materialName || "——";
      // 1. 先录入工序信息
      item.nodes.forEach((node: any) => {
        const processName = node.process?.processName || "";
        const createTime = node.process?.createTime || "";

        // 2. 遍历 inputNodes
        if (Array.isArray(node.inputNodes)) {
          node.inputNodes.forEach((input: any) => {
            result.push({
              processName,
              createTime,
              materialName,
              type: "input",
              inputType: input.inputType,
              inputPCF: input.inputPCF
            });
          });
        }

        // 3. 遍历 outputNodes
        if (Array.isArray(node.outputNodes)) {
          node.outputNodes.forEach((output: any) => {
            result.push({
              processName,
              createTime,
              materialName,
              type: "output",
              outputName: output.outputName,
              outputPCF: output.outputPCF
            });
          });
        }
      });
    });
    // 构建请求参数
    const requestData = {
      projectId: String(project.value.id),
      owner: project.value.companyName,
      productName: productName.value,
      projectStart: project.value.projectStart,
      projectEnd: project.value.projectEnd,
      aggregatedPCF: totalCarbonFootprint.value.toString(),
      aggregatedPCFUnit: "kgCO2eq",
      outMaterialData: Array.isArray(PCFs_outMaterial.value)
        ? PCFs_outMaterial.value.map((item: any) => ({
            materialName: item.materialName,
            PCF: item.PCF
          }))
        : [],
      processData: result
    };
    const stringifyData = JSON.stringify(requestData);
    // 调用接口
    const response = await axios.post(baseUrl + "/api/carbon/saveBlockchainDocument", {
      type: "LCA",
      docData: stringifyData,
      Sender: project.value.companyName,
      Recipient: project.value.companyName,
      docID: "",
      inDocs: ""
    });

    if (response.data.code === 200) {
      // 获取返回的 id 并存储到
      isLCAResultCreated.value = true; // 标记已成功创建
      const txId = response.data.data.txId;
      if (txId) {
        try {
          await axios.post(`${baseUrl}/api/carbon/saveTxId?projectId=${project.value.id}`, { TxId: txId });
          console.log(`已保存交易ID: ${txId} 到后端，projectId: ${project.value.id}`);
          return txId; // 返回交易ID
        } catch (e) {
          console.warn("保存txId到后端失败", e);
        }
      } else {
        console.warn("Response data does not contain an ID");
      }
    } else {
      console.error("创建LCA项目结果失败:", response.data.message);
    }
  } catch (error) {
    console.error("调用创建LCA项目结果接口出错:", error);
  } finally {
    isCreateLCARequestInProgress.value = false; // 无论成功失败都标记为已完成
  }
};

// 监听路由参数变化，仅在 projectId 变化时更新数据
watch(
  () => route.params.projectId,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      isDataLoaded.value = false; // 重置数据加载状态
      getProductInfo();
      fetchTotalPCF();
    }
  }
);

// 修改现有的 watch，在数据准备好时调用接口
watch(
  () => processData.value,
  newData => {
    if (newData && newData.length > 0) {
      window.requestAnimationFrame(async () => {
        initChart_Process();
        initChart_InandOut();
        initChart_outMaterial();
        // 当图表和数据都准备好后，调用创建LCA项目结果的接口
        const blockchainData = await ensureBlockchainInfo();
        if (blockchainData) {
          blockchainInfo.value = blockchainData;
        }
      });
    }
  },
  { deep: true }
);

watch(
  () => project.value,
  newProject => {
    if (newProject) {
      window.requestAnimationFrame(() => {
        initChart_InandOut();
        initChart_outMaterial();
      });
    }
  },
  { deep: true }
);

// 监视 eachProcessPCF，变化时初始化单元过程柱状图
watch(
  () => eachProcessPCF.value,
  newVal => {
    if (newVal && newVal.length > 0) {
      window.requestAnimationFrame(() => {
        initChart_Process();
      });
    }
  },
  { deep: true }
);

// 监视 processTotal 和 outMaterialTotal，变化时初始化内外比例饼状图
watch([() => processTotal.value, () => outMaterialTotal.value], ([newProcessTotal, newOutMaterialTotal]) => {
  if (newProcessTotal > 0 || newOutMaterialTotal > 0) {
    window.requestAnimationFrame(() => {
      initChart_InandOut();
    });
  }
});

// 组件卸载时清理
onBeforeUnmount(() => {
  // 原有的清理代码
  if (myChart_Process) {
    myChart_Process.dispose();
    myChart_Process = null;
  }
  if (myChart_InandOut) {
    myChart_InandOut.dispose();
    myChart_InandOut = null;
  }
  if (myChart_outMaterial) {
    myChart_outMaterial.dispose();
    myChart_outMaterial = null;
  }
});

// 格式化数字，保留两位小数，整数不显示小数点
const formatNumber = (num: string | number) => {
  const parsed = typeof num === "string" ? parseFloat(num) : num;
  return Number.isInteger(parsed) ? parsed.toString() : parsed.toFixed(2);
};
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  margin-bottom: 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.nav-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}
.nav-button:hover {
  background-color: #007d6a;
}
.steps-container {
  display: flex;
  justify-content: space-between;
  width: 80%;
  padding: 0 20px;
}
.step-box {
  position: relative;
  flex: 1;
  padding: 15px 10px;
  margin: 0 10px;
  color: #777777;
  text-align: center;
  cursor: pointer;
  background-color: #f9f9f9;
  border: 1px solid #dcdcdc;
  border-radius: 5px;
  transition: all 0.3s;
}
.step-box.active {
  font-weight: bold;
  color: #009688;
  background-color: #e6f5f3;
  border-color: #009688;
}

/* 确保非活动状态的步骤显示为默认样式 */
.step-box:not(.active) {
  color: #777777;
  background-color: #f9f9f9;
  border-color: #dcdcdc;
}

/* 每个步骤框的箭头 */
.step-box::after {
  position: absolute;
  top: 50%;
  right: -20px;
  font-size: 20px;
  color: #009688;
  content: "→";
  transform: translateY(-50%);
}
.step-box:last-child::after {
  visibility: hidden;
}
.impact-container {
  height: 100vh;
  padding: 16px;
  background-color: var(--el-bg-color-page);
}
.table-container {
  padding: 20px;
  margin-top: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  margin-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.process-cell,
.equipment-cell {
  display: flex;
  gap: 8px;
  align-items: center;
}
.emission-sources {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.source-item {
  padding: 4px 8px;
  font-size: 13px;
  border-radius: 4px;
}
.source-item.input {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-5);
}
.source-item.output {
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
  border: 1px solid var(--el-color-success-light-5);
}
.consumption-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.consumption-item {
  display: flex;
  gap: 8px;
  align-items: center;
}
.amount {
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.unit {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}
.divider {
  height: 1px;
  margin: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}
.source-type {
  padding: 8px;
  color: var(--el-text-color-regular);
}
:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-color-primary-light-9);
  --el-table-row-hover-bg-color: var(--el-color-primary-light-9);
  --el-table-row-height: auto;
  --el-table-padding: 12px;
}
:deep(.el-table__cell) {
  padding: 12px !important;
}
:deep(.el-table th) {
  font-weight: 600;
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: var(--el-color-primary-light-9);
}
.io-type {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.io-item {
  padding: 4px 8px;
  font-size: 13px;
  text-align: center;
  border-radius: 4px;
}
.io-item.input {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-5);
}
.io-item.output {
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
  border: 1px solid var(--el-color-success-light-5);
}
.header-buttons {
  display: flex;
  gap: 10px;
}
.calc-params-dialog :deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  max-height: 80vh;
}
.calc-params-dialog :deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
}
.method-select {
  padding: 20px;
}
.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
.el-descriptions {
  margin: 0;
}
:deep(.el-descriptions__cell) {
  padding: 8px 12px;
}
.factor-details {
  padding: 8px;
}
.factor-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.factor-select {
  display: flex;
  gap: 8px;
  align-items: center;
}
.selected-factor {
  font-weight: 600;
  color: var(--el-color-primary);
}
.no-factor {
  color: var(--el-text-color-secondary);
}
.factor-dialog :deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  max-height: 80vh;
}
.factor-dialog :deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
}
.echarts {
  width: 100%;
  height: 400px;
  min-height: 400px;
}
.product-info-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  margin: 20px;
  background-color: #f4f6f8;
  border-radius: 8px;
}
.info-card {
  padding: 16px 24px;
  margin: 20px 0;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgb(0 0 0 / 5%);
}
.info-content-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.product-name {
  display: flex;
  gap: 8px;
  align-items: center;
}
.info-label {
  font-size: 15px;
  color: #606266;
}
.info-value {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
.carbon-footprint {
  display: flex;
  gap: 12px;
  align-items: center;
}
.footprint-value {
  font-size: 20px;
  font-weight: bold;
  color: #009688;
}

/* 添加区块链表格背景 */
.blockchain-table {
  position: relative;
  background-color: transparent;
}
.blockchain-table::before {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 1;
  width: 400px;
  height: 400px;
  pointer-events: none;
  content: "";
  background-image: url("@/assets/icons/区块链图标.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  opacity: 0.1;
  transform: translate(-50%, -50%);
}
</style>
